- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathArrayIntersection.java
45 lines (33 loc) Β· 1021 Bytes
/
ArrayIntersection.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
packagesection16_Hashmap;
importjava.util.Arrays;
importjava.util.HashMap;
publicclassArrayIntersection {
publicstaticvoidmain(String[] args) {
int[] arr1 = { 5, 1, 3, 4, 7 };
int[] arr2 = { 2, 4, 3, 5, 7, 10, 15 };
int[] intersection = intersectionArrays(arr1, arr2);
System.out.println(Arrays.toString(intersection));
}
staticint[] intersectionArrays(int[] arr1, int[] arr2) {
HashMap<Integer, Integer> map = newHashMap<Integer, Integer>();
// constraints: all elements are unique in given individual array
for (inti = 0; i < arr1.length; i++) {
map.put(arr1[i], 1);
}
intintersectCount = 0;
// this loop can be avoided using ArrayList
for (inti = 0; i < arr2.length; i++) {
if (map.containsKey(arr2[i]))
intersectCount++;
}
int[] intersections = newint[intersectCount];
intindex = 0;
for (inti = 0; i < arr2.length; i++) {
if (map.containsKey(arr2[i])) {
intersections[index] = arr2[i];
index++;
}
}
returnintersections;
}
}